package routers

import (
	"gitee.com/zjlsliupei/ghelp"
	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/cookie"
	"github.com/gin-gonic/gin"
	adminController "go-web/controllers/admin"
	"net/http"
	"strings"
)

// view文件和静态文件缓存
func init() {
	registry(func(app *gin.Engine) {
		app.LoadHTMLGlob("views/*")
		// 静态文件
		app.Static("/static", "./static")
		// 设置、验证session
		store := cookie.NewStore([]byte("gadmin"))
		admin := app.Group("/admin", sessions.Sessions("gadmin", store), func(c *gin.Context) {
			if !ghelp.InArray(strings.ToLower(c.Request.URL.Path), []string{"/admin/login", "/admin/loginpost"}) {
				// 初始化session对象
				s := sessions.Default(c)
				uid, ok := s.Get("uid").(uint)
				if (!ok) || (uid <= 0) {
					c.Redirect(http.StatusFound, "/admin/login")
					c.Abort()
					return
				}
			}
			c.Next()
		})

		{
			admin.GET("/index", adminController.Index)
			admin.GET("/login", adminController.Login)
			admin.POST("/loginPost", adminController.LoginPost)
			admin.GET("/loginOut", adminController.LoginOut)
		}

	})
}
